﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VulnDBExplorer.Services;

namespace VulnDBExplorer.Forms
{
	public partial class ConsolePanel : UserControl, IConsole
	{
		private StringBuilder buffer;
		private bool dirty = false;
		private Timer t;

		public ConsolePanel() {
			InitializeComponent();
			DoubleBuffered = true;
			clearToolStripMenuItem.Click += (o, e) => clear();
			saveAsToolStripMenuItem.Click += new EventHandler(saveAsToolStripMenuItem_Click);
			t = new Timer() { Interval = 1000 };
			t.Tick += new EventHandler(updateTextBox);
			t.Start();
			clear();
		}

		//public String Text { get; set; }

		public override string ToString() {
			return Text;
		}

		internal void stopTimer() {
			if (t != null) t.Stop();
		}

		void updateTextBox(object sender, EventArgs e) {
			if (!dirty) return;
			lock (this) {
				textBox1.Text = buffer.ToString();
				dirty = false;
			}
			if (this.Visible) {
				textBox1.SelectionStart = textBox1.Text.Length;
				textBox1.ScrollToCaret();
			}
		}

		void saveAsToolStripMenuItem_Click(object sender, EventArgs e) {
			SaveFileDialog sf = new SaveFileDialog();
			sf.Title = "Save Console Messages...";
			sf.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
			if (sf.ShowDialog() == DialogResult.OK)
				System.IO.File.WriteAllText(sf.FileName, textBox1.Text);
		}

		public void clear() {
			lock (this) {
				buffer = new StringBuilder();
				dirty = true;
			}
		}

		#region IConsole Members

		void IConsole.write(string format, params object[] args) {
			string text = args.Length > 0 ? string.Format(format, args) : format;
			lock (this) {
				buffer.Append(text);
				dirty = true;
			}
		}

		void IConsole.writeLine(string format, params object[] args) {
			string text = args.Length > 0 ? string.Format(format, args) : format;
			lock (this) {
				buffer.AppendLine(text);
				dirty = true;
			}
		}

		void IConsole.log(string format, params object[] args) {
			DateTime dt = DateTime.Now;
			long tickPerSec = System.Diagnostics.Stopwatch.Frequency;
			string fraction = "000000" + ((dt.Ticks % tickPerSec) / 100).ToString();
			fraction = fraction.Substring(fraction.Length - 6, 6);
			(this as IConsole).writeLine(string.Format("[{0:hh:mm:ss}.{1}] {2}", dt,
				fraction, string.Format(format, args)));
		}

		#endregion
	}
}
